﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using UpdateManager.UserControls.Event;
using System.Windows.Controls.Primitives;
using System.Runtime.InteropServices;

namespace UpdateManager.UserControls {
    /// <summary>
    /// 下载项信息的交互逻辑
    /// </summary>
    public partial class UpdateItem : UserControl {

        #region 事件

        /// <summary>
        /// 复选框选择变换事件
        /// </summary>
        public event EventHandler<CheckedChangeEventArgs> OnCheckedChange;
        /// <summary>
        /// 开始下载事件
        /// </summary>
        public event EventHandler<DownloadEventArgs> OnStartDownload;
        /// <summary>
        /// 停止下载事件
        /// </summary>
        public event EventHandler<DownloadEventArgs> OnStopDownload;
        /// <summary>
        /// 暂停下载事件
        /// </summary>
        public event EventHandler<DownloadEventArgs> OnPauseDownload;
        /// <summary>
        /// 详情事件
        /// </summary>
        public event EventHandler<EventArgs> OnNotTip;

        #endregion

        /// <summary>
        /// 是否正在下载
        /// </summary>
        private bool isDownloading = false;
        /// <summary>
        /// 是否已经下载
        /// </summary>
        private bool hasDownloaded = false;

        /// <summary>
        /// 程序集子项信息
        /// </summary>
        private AssemblyItemInfo assemblyItem = new AssemblyItemInfo();

        /// <summary>
        /// 创建一个<see cref="UpdateItem"/>实例
        /// </summary>
        public UpdateItem() {
            InitializeComponent();

            this.MouseEnter += new MouseEventHandler(UserControl_MouseEnter);
            this.MouseLeave += new MouseEventHandler(UserControl_MouseLeave);
            //this.MouseUp += new MouseButtonEventHandler(UserControl_MouseUp);

            this.chkSelect.Checked += new RoutedEventHandler(chkSelect_Checked);
            this.chkSelect.Unchecked += new RoutedEventHandler(chkSelect_Unchecked);

            this.btnDownload.Click += new RoutedEventHandler(btnDownload_Click);
            this.imgStart.MouseUp += new MouseButtonEventHandler(imgStart_MouseUp);
            this.imgStop.MouseDown += new MouseButtonEventHandler(imgStop_MouseUp);
            this.lnkMore.Click += new RoutedEventHandler(lnkMore_Click);
            this.imgNotTip.MouseUp += new MouseButtonEventHandler(imgNotTip_MouseUp);
        }

        

        /// <summary>
        /// 重置
        /// </summary>
        public void Reset() {
            this.progressBar1.Value = 0;
            this.txtSpead.Text = "等待下载...";
        }

        public void DoDownload() {
            this.btnDownload_Click(this.btnDownload, null);
        }


        private static Popup pop = null;

        /// <summary>
        /// 详细信息单击事件方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lnkMore_Click(object sender, RoutedEventArgs e) 
        {
            if (pop == null) {
                pop = new Popup();

                //初始化详细信息窗体
                ItemDetails details = new ItemDetails();
                //赋值
                details.Title = this.AssemblyItem.AssemblyText;
                details.Details = this.AssemblyItem.Information;
                //注册关闭按钮事件
                details.imgClose.MouseDown += new MouseButtonEventHandler(ItemDetailImgClose_MouseDown);

                //设置弹出层的子面板
                pop.Child = details;
                //设置弹出位置
                pop.VerticalOffset = System.Windows.Forms.Control.MousePosition.Y + 10;
                pop.HorizontalOffset = System.Windows.Forms.Control.MousePosition.X + 20;
                //弹出显示
                pop.IsOpen = true;
            } else {
                //设置弹出位置
                pop.VerticalOffset = System.Windows.Forms.Control.MousePosition.Y + 10;
                pop.HorizontalOffset = System.Windows.Forms.Control.MousePosition.X + 20;

                ((ItemDetails)pop.Child).Title = this.AssemblyItem.AssemblyText;
                ((ItemDetails)pop.Child).Details = this.AssemblyItem.Information;
            }
        }

        public void ItemDetailImgClose_MouseDown(object sender, MouseButtonEventArgs e) {
            // 关闭弹出层
            pop.IsOpen = false;

            pop = null;
        }

        #region 属性

        /// <summary>
        /// 获取是否被选中
        /// </summary>
        public bool IsChecked {
            get {
                return (bool)this.chkSelect.IsChecked;
            }
        }

        /// <summary>
        /// 获取是否正在下载
        /// </summary>
        public bool IsDownloading {
            get {
                return this.isDownloading;
            }
            set {
                this.isDownloading = value;
            }
        }

        /// <summary>
        /// 获取或设置是否已经下载
        /// </summary>
        public bool HasDownloaded {
            get {
                return hasDownloaded;
            }
            set {
                hasDownloaded = value;
            }
        }

        /// <summary>
        /// 获取或设置程序集子项
        /// </summary>
        public AssemblyItemInfo AssemblyItem {
            get { return assemblyItem; }
            set {
                assemblyItem = value;

                this.txtAssemblyText.Text = this.assemblyItem.AssemblyText;

                if (this.assemblyItem.Information.Length > 20) {
                    this.runAssemblyInfo.Text = this.assemblyItem.Information.Trim().Substring(0, 20) + "... ";
                } else {
                    this.runAssemblyInfo.Text = this.assemblyItem.Information;
                }
                this.txtNewVersion.Text = String.Format("最新：{0}", this.assemblyItem.Version);
                this.txtOldVersion.Text = String.Format("已装：{0}",
                    String.IsNullOrEmpty(this.assemblyItem.OldVersion) ? "尚未安装" : this.assemblyItem.OldVersion);
                this.txtPublishDate.Text = this.assemblyItem.PublishDate.ToString("yyyy-MM-dd");
                this.txtSize.Text = this.assemblyItem.Size;
                this.imgAssemblyIcon.Source = new BitmapImage(new Uri(this.assemblyItem.IconUrl, UriKind.Absolute));

                bool view = (this.assemblyItem.Version == this.assemblyItem.OldVersion) || this.assemblyItem.IsNew;
                this.txtIsNew.Visibility = view ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
                this.chkSelect.IsEnabled = view ? false : true;
                this.btnDownload.Visibility = view ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible;
                this.imgNotTip.Visibility = this.btnDownload.Visibility;

                if (this.assemblyItem.IsNew) {
                    this.txtIsNew.Text = "即将发布";
                } else if(this.assemblyItem.Version == this.assemblyItem.OldVersion) {
                    this.txtIsNew.Text = "已安装";
                }

                if (this.AssemblyItem.IsTip) {
                    this.imgNotTip.Source = new BitmapImage(new Uri(@"..\Resources\note_delete.png", UriKind.Relative));
                    this.imgNotTip.ToolTip = "取消更新提示";
                } else {
                    this.imgNotTip.Source = new BitmapImage(new Uri(@"..\Resources\note_add.png", UriKind.Relative));
                    this.imgNotTip.ToolTip = "更新提示";
                }
            }
        }

        #endregion

        #region 页面控件事件方法

        /// <summary>
        /// 控件鼠标进入事件方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserControl_MouseEnter(object sender, MouseEventArgs e) {
            //鼠标进入更改背景颜色为：#FFEAF9FE
            this.Background = new SolidColorBrush(Color.FromArgb(0xFF, 0xEA, 0xF9, 0xFE));
        }

        /// <summary>
        /// 控件鼠标离开事件方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserControl_MouseLeave(object sender, MouseEventArgs e) {
            //鼠标离开，判断是否被选择
            if (!(bool)this.chkSelect.IsChecked) {
                //没被选择取消背景颜色
                this.Background = null;
            } else {
                //设置被选择背景颜色为：#FFFEFCD6
                this.Background = new SolidColorBrush(Color.FromArgb(0xFF, 0xFF, 0xFC, 0xD6));
            }
        }

        /// <summary>
        /// 控件鼠标抬起（单击）事件方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserControl_MouseUp(object sender, MouseButtonEventArgs e) {
            if (this.chkSelect.IsEnabled) {
                //控件单击，改变选择状态
                this.chkSelect.IsChecked = !(bool)this.chkSelect.IsChecked;

                //判断是否被选择
                if (!(bool)this.chkSelect.IsChecked) {
                    //没被选择，设置背景颜色为：#FFEAF9FE
                    this.Background = new SolidColorBrush(Color.FromArgb(0xFF, 0xEA, 0xF9, 0xFE));
                } else {
                    //设置被选择背景颜色为：#FFFEFCD6
                    this.Background = new SolidColorBrush(Color.FromArgb(0xFF, 0xFF, 0xFC, 0xD6));
                }

                //调用事件
                if (this.OnCheckedChange != null) {
                    this.OnCheckedChange(this, new CheckedChangeEventArgs() { IsChecked = (bool)this.chkSelect.IsChecked });
                }
            }
        }

        /// <summary>
        /// 选择框选择事件方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chkSelect_Checked(object sender, RoutedEventArgs e) {
            //设置被选择背景颜色为：#FFFEFCD6
            this.Background = new SolidColorBrush(Color.FromArgb(0xFF, 0xFF, 0xFC, 0xD6));

            //调用事件
            if (this.OnCheckedChange != null) {
                this.OnCheckedChange(this, new CheckedChangeEventArgs() { IsChecked = true });
            }
        }

        /// <summary>
        /// 选择框取消选择事件方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chkSelect_Unchecked(object sender, RoutedEventArgs e) {
            //判断鼠标是否正位于该控件中
            if (this.IsMouseOver) {
                //鼠标进入更改背景颜色为：#FFEAF9FE
                this.Background = new SolidColorBrush(Color.FromArgb(0xFF, 0xEA, 0xF9, 0xFE));
            } else {
                //取消背景颜色
                this.Background = null;
            }

            //调用事件
            if (this.OnCheckedChange != null) {
                this.OnCheckedChange(this, new CheckedChangeEventArgs() { IsChecked = false });
            }
        }

        /// <summary>
        /// 下载按钮单击事件方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDownload_Click(object sender, RoutedEventArgs e) {
            //设置开始/暂停图片按钮图标为暂停图标
            this.imgStart.Source = new BitmapImage(new Uri(@"..\Resources\pause.png", UriKind.Relative));

            //显示下载进度相关组件
            this.grInfo.Visibility = System.Windows.Visibility.Collapsed;
            this.grDownload.Visibility = System.Windows.Visibility.Visible;

            //赋值开始下载
            this.isDownloading = true;

            //调用事件
            if (this.OnStartDownload != null) {
                this.OnStartDownload(
                    this, new DownloadEventArgs() { Url = this.assemblyItem.UpdateUrl, IsDownloading = true });
            }
        }

        /// <summary>
        /// 暂停/开始图片按钮鼠抬起（单击）事件方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void imgStart_MouseUp(object sender, MouseButtonEventArgs e) {
            if (this.isDownloading) {
                this.imgStart.Source = new BitmapImage(new Uri(@"..\Resources\start.png", UriKind.Relative));
                this.isDownloading = false;

                //调用事件
                if (this.OnPauseDownload != null) {
                    this.OnPauseDownload(
                        this, new DownloadEventArgs() { Url = this.assemblyItem.UpdateUrl, IsDownloading = false });
                }

                this.txtSpead.Text = "暂停";
            } else {
                this.imgStart.Source = new BitmapImage(new Uri(@"..\Resources\pause.png", UriKind.Relative));

                this.isDownloading = true;

                //调用事件
                if (this.OnStartDownload != null) {
                    this.OnStartDownload(
                        this, new DownloadEventArgs() { Url = this.assemblyItem.UpdateUrl, IsDownloading = true });
                }
            }
        }

        /// <summary>
        /// 停止图片按钮鼠抬起（单击）事件方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void imgStop_MouseUp(object sender, MouseButtonEventArgs e) {
            //显示下载信息相关组件
            this.grInfo.Visibility = System.Windows.Visibility.Visible;
            this.grDownload.Visibility = System.Windows.Visibility.Collapsed;

            //赋值开始下载
            this.isDownloading = false;

            //调用事件
            if (this.OnStopDownload != null) {
                this.OnStopDownload(
                    this, new DownloadEventArgs() { Url = this.assemblyItem.UpdateUrl, IsDownloading = false });
            }
        }

        /// <summary>
        /// 取消提示按钮鼠标抬起事件方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void imgNotTip_MouseUp(object sender, MouseButtonEventArgs e) {
            this.AssemblyItem.IsTip = !this.AssemblyItem.IsTip;

            if (this.AssemblyItem.IsTip) {
                this.imgNotTip.Source = new BitmapImage(new Uri(@"..\Resources\note_delete.png", UriKind.Relative));
                this.imgNotTip.ToolTip = "取消更新提示";
            } else {
                this.imgNotTip.Source = new BitmapImage(new Uri(@"..\Resources\note_add.png", UriKind.Relative));
                this.imgNotTip.ToolTip = "更新提示";
            }

            if (this.OnNotTip != null) {
                this.OnNotTip(this, new EventArgs());
            }
        }
        #endregion
        
    }
}
